//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { Modal,  Tree } from "antd";
import { useStores } from "@/hooks";
import type { DataNode } from "antd/lib/tree";
import s from "./OrgTree.module.less";

export interface SelectDepartMentModalProps {
    skipDepartMentIdList: string[];
    onCancel: () => void;
    onOk: (departMentId: string) => void;
}

const SelectDepartMentModal = (props: SelectDepartMentModalProps) => {
    const orgStore = useStores('orgStore');

    const [treeNodeList, setTreeNodeList] = useState([] as DataNode[]);
    const [selectKey, setSelectKey] = useState("");

    const setupTreeNode = (nodeList: DataNode[], parentDepartMentId: string) => {
        //处理下属部门
        for (const departMent of orgStore.departMentList) {
            if (departMent.parent_depart_ment_id != parentDepartMentId) {
                continue;
            }
            if (props.skipDepartMentIdList.includes(departMent.depart_ment_id)) {
                continue;
            }
            const subNode: DataNode = {
                key: departMent.depart_ment_id,
                title: departMent.depart_ment_name,
                children: [],
                selectable: true,
            }
            nodeList.push(subNode);
            setupTreeNode(subNode.children!, departMent.depart_ment_id);
        }

    }

    const initTree = async () => {
        const tmpNodeList = [] as DataNode[];
        setupTreeNode(tmpNodeList, "");
        setTreeNodeList([{
            key: "",
            title: "总部门",
            children: tmpNodeList,
            checkable: false,
            selectable: true,
        }]);
    };

    useEffect(() => {
        initTree();
    }, [orgStore.departMentList, orgStore.memberList]);

    return (
        <Modal open title="选择部门" mask={false}
            className={s.treeWrap}
            okText="选择" okButtonProps={{ disabled: props.skipDepartMentIdList.includes(selectKey) }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onOk(selectKey);
            }}>
            <Tree expandedKeys={["", ...orgStore.departMentList.map(item => item.depart_ment_id)]}
                selectedKeys={[selectKey]} treeData={treeNodeList} showIcon
                onSelect={keys => {
                    const tmpList = keys.filter(key => key != selectKey);
                    if (tmpList.length > 0) {
                        setSelectKey(tmpList[0] as string);
                    }
                }} />
        </Modal>
    );
};

export default observer(SelectDepartMentModal);